package org.lc.stk.dao.course;

import java.util.List;
import java.util.Optional;

import org.lc.stk.model.course.Chapter;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface ChapterRepository extends JpaRepository<Chapter, Integer>, JpaSpecificationExecutor<Chapter> {
    /**
     * 根据课程ID查询直接子章节（父章节为空的）
     */
    List<Chapter> findByCourseIdAndParentIsNull(Integer courseId, Sort sort);

    /**
     * 根据父章节ID查询子章节
     */
    List<Chapter> findByParentId(Integer parentId, Sort sort);

    /**
     * 根据课程ID和章节序号查询章节
     */
    Optional<Chapter> findByCourseIdAndSort(Integer courseId, Integer sort);

    /**
     * 检查同级章节中是否存在相同的排序号
     */
    boolean existsByCourseIdAndParentIdAndSort(Integer courseId, Integer parentId, Integer sort);

    /**
     * 获取同级章节中最大的排序号
     */
    @Query("SELECT MAX(c.sort) FROM Chapter c WHERE c.course.id = :courseId AND c.parent.id = :parentId")
    Optional<Integer> findMaxSortByParentId(@Param("courseId") Integer courseId, 
                                          @Param("parentId") Integer parentId);

    /**
     * 获取根章节的最大排序号
     */
    @Query("SELECT MAX(c.sort) FROM Chapter c WHERE c.course.id = :courseId AND c.parent IS NULL")
    Optional<Integer> findMaxRootSort(@Param("courseId") Integer courseId);

    /**
     * 根据课程ID删除所有章节
     */
    void deleteByCourseId(Integer courseId);

    /**
     * 检查课程是否存在章节
     */
    boolean existsByCourseId(Integer courseId);

    /**
     * 根据名称模糊查询章节
     */
    List<Chapter> findByCourseIdAndNameContaining(Integer courseId, String name, Sort sort);
}